package com.hxgz.steel.controller.backend;


import com.hxgz.steel.common.Const;
import com.hxgz.steel.common.Const.RedisCacheExtime;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.controller.portal.UserContorller;
import com.hxgz.steel.domain.BackendUser;
import com.hxgz.steel.domain.User;
import com.hxgz.steel.service.BackendLoginService;
import com.hxgz.steel.util.CookieUtil;
import com.hxgz.steel.util.JsonUtil;
import com.hxgz.steel.util.RedisPoolUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("portalLogin")
@Api(tags = "BackendLoginController", description = "后台-登入")
public class BackendLoginController {

  private static  final Logger logger = LoggerFactory.getLogger(BackendLoginController.class);

  @Autowired
  BackendLoginService backendLoginService;


  @RequestMapping(value = "login.do", method = RequestMethod.POST)
  @ApiOperation("后台用户登入")
  public ServerResponse portalLogin(HttpServletResponse httpServletResponse, HttpSession session,
      String username, String password) {
    ServerResponse<BackendUser> backendUser = backendLoginService.userLogin(username, password);
    if (backendUser.isSuccess()) {
      CookieUtil.writeBackLoginToken(httpServletResponse, session.getId());
      RedisPoolUtil.set(session.getId(), JsonUtil.obj2String(backendUser.getData()));
    }
    return backendUser;
  }


  @RequestMapping(value = "checkLogin.do", method = RequestMethod.POST)
  @ApiOperation("后台检验用户登入")
  public ServerResponse checkLogin(HttpServletRequest httpServletRequest) {
    User user = Const.checkBackUserLogin(httpServletRequest);
    if (user == null) {
      return ServerResponse.createByErrorMessage("用户未登陆,无法获取当前信息");
    } else {
      user.setPassword("");
      return ServerResponse.createBySuccess(user);
    }
  }

  @RequestMapping(value = "loginOut.do",method = RequestMethod.POST)
  @ApiOperation("后台用户登出")
  public ServerResponse loginOut(HttpServletRequest request,HttpServletResponse response){
    String loginToken = CookieUtil.readBackLoginToken(request);
    CookieUtil.delLoginToken(request, response);
    RedisPoolUtil.del(loginToken);
    return ServerResponse.createBySuccess("登出成功");
  }

}
